package com.ctsi.ssdc.service.impl;

import com.ctsi.ssdc.aop.TimeCostLog;
import com.ctsi.ssdc.common.CallBackResult;
import com.ctsi.ssdc.mapper.*;
import com.ctsi.ssdc.service.*;
import com.ctsi.ssdc.entity.EconomicIndicators;
import com.ctsi.ssdc.entity.FixedInvestment;
import com.ctsi.ssdc.entity.IndustrialEconomicIndicators;
import com.ctsi.ssdc.entity.SocialRetailSales;
import com.ctsi.ssdc.entity.SubDistrictTownFixedInvestment;
import com.ctsi.ssdc.entity.SubDistrictTownIndustrialInvestment;
import com.ctsi.ssdc.entity.SubDistrictTownIndustry;
import com.ctsi.ssdc.entity.TradeAndServiceIndustry;
import com.ctsi.ssdc.entity.*;
import com.ctsi.ssdc.util.ExcelUtil;
import com.ctsi.ssdc.utils.ExcelThreadPool;
import com.ctsi.ssdc.utils.ExcelUtils;
import com.ctsi.ssdc.utils.TimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ExcelServiceImpl implements ExcelService {
    //昆山旅游度假区主要经济指标
    @Resource
    private ExcelService excelService;
    @Resource
    private ExcelMapper excelMapper;
    @Resource
    private EconomicIndicatorsService economicIndicatorsService;
    @Resource
    private SubDistrictTownIndustryService subDistrictTownIndustryService;
    @Resource
    private IndustrialEconomicIndicatorsService industrialEconomicIndicatorsService;
    @Resource
    private SubDistrictTownFixedInvestmentService subDistrictTownFixedInvestmentService;
    @Resource
    private SubDistrictTownIndustrialInvestmentService subDistrictTownIndustrialInvestmentService;
    @Resource
    private FixedInvestmentService fixedInvestmentService;
    @Resource
    private SocialRetailSalesService socialRetailSalesService;
    @Resource
    private TradeAndServiceIndustryService tradeAndServiceIndustryService;
    @Resource
    private Excel08Service excel08Service;
    @Resource
    private Excel02Service excel02Service;
    @Resource
    private Excel11Service excel11Service;
    @Resource
    private Excel12Service excel12Service;
    @Resource
    private Excel09Service excel09Service;
    @Resource
    private Excel14Service excel14Service;
    @Resource
    private Excel15Service excel15Service;
    @Resource
    private TransactionTemplate transactionTemplate;

    @Override
    @TimeCostLog
    public boolean uploadExcel(MultipartFile uploadExcel, Date date) {
        Workbook wb = ExcelUtils.getWorkbook(uploadExcel);
        ExcelThreadPool threadPool = new ExcelThreadPool(15, transactionTemplate);
        PlatformTransactionManager transactionManager = transactionTemplate.getTransactionManager();
        TransactionStatus status = transactionManager.getTransaction(transactionTemplate);
        threadPool.submit(() -> excelService.uploadEconomicIndicatorsExcel(wb, "1", 3, date));
        threadPool.submit(() -> excelService.uploadSubDistrictTownIndustryExcel(wb, "分区镇工业", 3, date));
        threadPool.submit(() -> excelService.uploadIndustrialEconomicIndicatorsExcel(wb, "工业经济主要指标", 3, date));
        threadPool.submit(() -> excelService.uploadSubDistrictTownFixedInvestmentExcel(wb, "分区镇固定资产", 3, date));
        threadPool.submit(() -> excelService.uploadSubDistrictTownIndustrialInvestmentExcel(wb, "分区镇工业投资", 3, date));
        threadPool.submit(() -> excelService.uploadFixedInvestmentExcel(wb, "固投", 3, date));
        threadPool.submit(() -> excelService.uploadSocialRetailSalesExcel(wb, "分区镇社零额", 3, date));
        threadPool.submit(() -> excelService.uploadTradeAndServiceIndustryExcel(wb, "贸易及服务业", 3, date));
        threadPool.submit(() -> excelService.uploadExcel02(wb, "2分区镇一般公共预算收入", 4, date));
        threadPool.submit(() -> excelService.uploadExcel08(wb, "8基础表工业分行业", 2, date));
        threadPool.submit(() -> excelService.uploadExcel09(wb, "9基础表工业分行业", 2, date));
        threadPool.submit(() -> excelService.uploadExcel11(wb, "11基础表投资", 2, date));
        threadPool.submit(() -> excelService.uploadExcel12(wb, "12基础表投资", 2, date));
        threadPool.submit(() -> excelService.uploadExcel14(wb, "14基础表服务业分行业", 2, date));
        threadPool.submit(() -> excelService.uploadExcel15(wb, "15基础表贸易分行业", 2, date));
        boolean result = threadPool.await(() -> excelService.removeAllExcel(date));
        transactionManager.commit(status);
        if (result) {
            // 计算
            try {
                transactionTemplate.execute(new TransactionCallbackWithoutResult() {
                    @Override
                    protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                        excelService.calculateExcel(date);
                    }
                });
            } catch (Exception e) {
                log.error("计算数据发生了故障!(自动回滚)");
                e.printStackTrace();
                excelService.removeAllExcel(date);
//            transactionManager.rollback(status);
                return false;
            }
        }
        return result;
    }

    /**
     * 上传文件
     *
     * @param wb            表格
     * @param sheetName
     * @param startReadLine 数据开始行数
     * @param date          数据日期
     * @return
     */
    @Override
    public CallBackResult uploadEconomicIndicatorsExcel(Workbook wb, String sheetName, int startReadLine, Date date) {
        try {
            List<EconomicIndicators> tList = ExcelUtils.importExcel(wb, sheetName, startReadLine, date, EconomicIndicators.class,
                    /**
                     * index: 当前列
                     * economicIndicators: 数据对象
                     * trim: 表格数据
                     */
                    (index, economicIndicators, trim) -> {
                        switch (index) {
                            case 0:
                                economicIndicators.setIndicators(trim);
                                break;
                            case 1:
                                economicIndicators.setUnit(trim);
                                break;
                            case 2:
                                economicIndicators.setThisMonth(ExcelUtils.parseDouble(trim));
                                break;
                            case 3:
                                economicIndicators.setAccumulate(ExcelUtils.parseDouble(trim));
                                break;
                            case 4:
                                economicIndicators.setMonthOnMonth(ExcelUtils.parseDouble(trim));
                                break;
                            case 5:
                                economicIndicators.setTotal(trim);
                                break;
                            case 6:
                                economicIndicators.setGrowthRate(trim);
                                break;
                            case 7:
                                economicIndicators.setSchedule(ExcelUtils.parseDouble(trim));
                                break;
                            default:
                                return null;
                        }
                        return economicIndicators;
                    });
            economicIndicatorsService.insertBatch(tList);
            return CallBackResult.ok();
        } catch (Exception e) {
            return CallBackResult.fail(e);
        }
    }


    @Override
    public CallBackResult uploadSubDistrictTownIndustryExcel(Workbook wb, String sheetName, int startReadLine, Date date) {
        try {
            List<SubDistrictTownIndustry> tList = ExcelUtils.importExcel(wb, sheetName, startReadLine, date, SubDistrictTownIndustry.class,
                    (index, subDistrictTownIndustry, trim) -> {
                        switch (index) {
                            case 0:
                                subDistrictTownIndustry.setIndicators(trim);
                                break;
                            case 1:
                                subDistrictTownIndustry.setThisMonth(ExcelUtils.parseDouble(trim));
                                break;
                            case 2:
                                subDistrictTownIndustry.setAccumulate(ExcelUtils.parseDouble(trim));
                                break;
                            case 3:
                                subDistrictTownIndustry.setMonthOnMonth(ExcelUtils.parseDouble(trim));
                                break;
                            case 4:
                                subDistrictTownIndustry.setRatio(ExcelUtils.parseDouble(trim));
                                break;
                            case 5:
                                subDistrictTownIndustry.setGrowthRanking(ExcelUtils.parseInteger(trim));
                                break;
                            default:
                                return null;

                        }
                        return subDistrictTownIndustry;
                    });

            subDistrictTownIndustryService.insertBatch(tList);
            return CallBackResult.ok();
        } catch (Exception e) {
            return CallBackResult.fail(e);
        }

    }

    @Override
    @TimeCostLog
    public CallBackResult uploadIndustrialEconomicIndicatorsExcel(Workbook wb, String sheetName, int startReadLine, Date date) {
        try {
            List<IndustrialEconomicIndicators> tList = ExcelUtils.importExcel(wb, sheetName, startReadLine, date, IndustrialEconomicIndicators.class,
                    (index, industrialEconomicIndicators, trim) -> {
                        switch (index) {
                            case 0:
                                industrialEconomicIndicators.setIndicators(trim);
                                break;
                            case 1:
                                industrialEconomicIndicators.setThisMonth(ExcelUtils.parseDouble(trim));
                                break;
                            case 2:
                                industrialEconomicIndicators.setAccumulate(ExcelUtils.parseDouble(trim));
                                break;
                            case 3:
                                industrialEconomicIndicators.setMonthOnMonth(ExcelUtils.parseDouble(trim));
                                break;
                            default:
                                return null;

                        }
                        return industrialEconomicIndicators;
                    });
            industrialEconomicIndicatorsService.insertBatch(tList);
            return CallBackResult.ok();
        } catch (Exception e) {
            return CallBackResult.fail(e);
        }


    }

    @Override
    @TimeCostLog
    public CallBackResult uploadSubDistrictTownFixedInvestmentExcel(Workbook wb, String sheetName, int startReadLine, Date date) {
        try {
            List<SubDistrictTownFixedInvestment> tList = ExcelUtils.importExcel(wb, sheetName, startReadLine, date, SubDistrictTownFixedInvestment.class,
                    (index, subDistrictTownFixedInvestment, trim) -> {
                        switch (index) {
                            case 0:
                                subDistrictTownFixedInvestment.setIndicators(trim);
                                break;
                            case 1:
                                subDistrictTownFixedInvestment.setThisMonth(ExcelUtils.parseDouble(trim));
                                break;
                            case 2:
                                subDistrictTownFixedInvestment.setAccumulate(ExcelUtils.parseDouble(trim));
                                break;
                            case 3:
                                subDistrictTownFixedInvestment.setMonthOnMonth(ExcelUtils.parseDouble(trim));
                                break;
                            case 4:
                                subDistrictTownFixedInvestment.setGrowthRanking(ExcelUtils.parseInteger(trim));
                                break;
                            default:
                                return null;
                        }
                        return subDistrictTownFixedInvestment;
                    });

            subDistrictTownFixedInvestmentService.insertBatch(tList);
            return CallBackResult.ok();
        } catch (Exception e) {
            return CallBackResult.fail(e);
        }

    }

    @Override
    @TimeCostLog
    public CallBackResult uploadSubDistrictTownIndustrialInvestmentExcel(Workbook wb, String sheetName, int startReadLine, Date date) {
        try {
            List<SubDistrictTownIndustrialInvestment> tList = ExcelUtils.importExcel(wb, sheetName, startReadLine, date, SubDistrictTownIndustrialInvestment.class,
                    (index, subDistrictTownIndustrialInvestment, trim) -> {
                        switch (index) {
                            case 0:
                                subDistrictTownIndustrialInvestment.setIndicators(trim);
                                break;
                            case 1:
                                subDistrictTownIndustrialInvestment.setThisMonth(ExcelUtils.parseDouble(trim));
                                break;
                            case 2:
                                subDistrictTownIndustrialInvestment.setAccumulate(ExcelUtils.parseDouble(trim));
                                break;
                            case 3:
                                subDistrictTownIndustrialInvestment.setMonthOnMonth(ExcelUtils.parseDouble(trim));
                                break;
                            case 4:
                                subDistrictTownIndustrialInvestment.setGrowthRanking(ExcelUtils.parseInteger(trim));
                                break;
                            default:
                                return null;
                        }
                        return subDistrictTownIndustrialInvestment;
                    });

            subDistrictTownIndustrialInvestmentService.insertBatch(tList);
            return CallBackResult.ok();
        } catch (Exception e) {
            return CallBackResult.fail(e);
        }

    }

    @Override
    @TimeCostLog
    public CallBackResult uploadFixedInvestmentExcel(Workbook wb, String sheetName, int startReadLine, Date date) {
        try {
            List<FixedInvestment> tList = ExcelUtils.importExcel(wb, sheetName, startReadLine, date, FixedInvestment.class,
                    (index, fixedInvestment, trim) -> {
                        switch (index) {
                            case 0:
                                fixedInvestment.setIndicators(trim);
                                break;
                            case 1:
                                fixedInvestment.setThisMonth(ExcelUtils.parseDouble(trim));
                                break;
                            case 2:
                                fixedInvestment.setAccumulate(ExcelUtils.parseDouble(trim));
                                break;
                            case 3:
                                fixedInvestment.setMonthOnMonth(ExcelUtils.parseDouble(trim));
                                break;
                            default:
                                return null;
                        }
                        return fixedInvestment;
                    });

            fixedInvestmentService.insertBatch(tList);
            return CallBackResult.ok();
        } catch (Exception e) {
            return CallBackResult.fail(e);
        }

    }

    @Override
    @TimeCostLog
    public CallBackResult uploadSocialRetailSalesExcel(Workbook wb, String sheetName, int startReadLine, Date date) {
        try {
            List<SocialRetailSales> tList = ExcelUtils.importExcel(wb, sheetName, startReadLine, date, SocialRetailSales.class,
                    (index, socialRetailSales, trim) -> {
                        switch (index) {
                            case 0:
                                socialRetailSales.setIndicators(trim);
                                break;
                            case 1:
                                socialRetailSales.setThisMonth(ExcelUtils.parseDouble(trim));
                                break;
                            case 2:
                                socialRetailSales.setAccumulate(ExcelUtils.parseDouble(trim));
                                break;
                            case 3:
                                socialRetailSales.setMonthOnMonth(ExcelUtils.parseDouble(trim));
                                break;
                            case 4:
                                socialRetailSales.setGrowthRanking(ExcelUtils.parseInteger(trim));
                                break;
                            default:
                                return null;
                        }
                        return socialRetailSales;
                    });

            socialRetailSalesService.insertBatch(tList);
            return CallBackResult.ok();
        } catch (Exception e) {
            return CallBackResult.fail(e);
        }

    }

    @Override
    @TimeCostLog
    public CallBackResult uploadTradeAndServiceIndustryExcel(Workbook wb, String sheetName, int startReadLine, Date date) {
        try {
            List<TradeAndServiceIndustry> tList = ExcelUtils.importExcel(wb, sheetName, startReadLine, date, TradeAndServiceIndustry.class,
                    (index, tradeAndServiceIndustry, trim) -> {
                        switch (index) {
                            case 0:
                                tradeAndServiceIndustry.setIndicators(trim);
                                break;
                            case 1:
                                tradeAndServiceIndustry.setThisMonth(ExcelUtils.parseDouble(trim));
                                break;
                            case 2:
                                tradeAndServiceIndustry.setAccumulate(ExcelUtils.parseDouble(trim));
                                break;
                            case 3:
                                tradeAndServiceIndustry.setMonthOnMonth(ExcelUtils.parseDouble(trim));
                                break;
                            default:
                                return null;
                        }
                        tradeAndServiceIndustry.setStatisticalTime(new Date());
                        return tradeAndServiceIndustry;
                    });

            tradeAndServiceIndustryService.insertBatch(tList);
            return CallBackResult.ok();
        } catch (Exception e) {
            return CallBackResult.fail(e);
        }

    }

    @Override
    @TimeCostLog
    public CallBackResult uploadExcel02(Workbook wb, String sheetName, int startReadLine, Date date) {
        try {
            List<Excel02> tList = ExcelUtils.importExcel(wb, sheetName, startReadLine, date, Excel02.class,
                    (index, excel02, trim) -> {
                        switch (index) {
                            case 0:
                                excel02.setIndicators(trim);
                            case 1:
                                excel02.setCurrentAchievements(ExcelUtils.parseDouble(trim));
                                break;
                            case 2:
                                excel02.setCurrentIncrease(ExcelUtils.parseDouble(trim));
                                break;
                            case 3:
                                excel02.setAccumulateAchievements(ExcelUtils.parseDouble(trim));
                                break;
                            case 4:
                                excel02.setAccumulateIncrease(ExcelUtils.parseDouble(trim));
                                break;
                            case 5:
                                excel02.setAccumulatedTaxRatio(ExcelUtils.parseDouble(trim));
                                break;
                            case 6:
                                excel02.setGrowthRanking(ExcelUtils.parseInteger(trim));
                                break;
                            default:
                                return null;
                        }
                        System.out.println(excel02);
                        return excel02;
                    });

            excel02Service.insertBatch(tList);
            return CallBackResult.ok();
        } catch (Exception e) {
            return CallBackResult.fail(e);
        }

    }

    @Override
    @TimeCostLog
    public CallBackResult uploadExcel08(Workbook wb, String sheetName, int startReadLine, Date date) {
        try {
            List<Excel08> tList = ExcelUtils.importExcel(wb, sheetName, startReadLine, date, Excel08.class,
                    (index, excel08, trim) -> {
                        switch (index) {
                            case 0:
                                excel08.setNumber(ExcelUtils.parseInteger(trim));
                            case 1:
                                excel08.setName(trim);
                                break;
                            case 2:
                                if (trim != null && trim.substring(trim.length() - 1).equals("镇"))
                                    trim = trim.substring(0, trim.length() - 1);
                                excel08.setArea(trim);
                                break;
                            case 3:
                                excel08.setOrganizationcode(trim);
                                break;
                            case 4:
                                excel08.setIndustrycode(ExcelUtils.parseInteger(trim));
                                break;
                            case 5:
                                excel08.setType(ExcelUtils.parseInteger(trim));
                                break;
                            case 6:
                                excel08.setGyczCurrentmonth(ExcelUtils.parseDouble(trim));
                                break;
                            case 7:
                                excel08.setGyczPreviousmonth(ExcelUtils.parseDouble(trim));
                                break;
                            case 8:
                                excel08.setGyczMonthonmonth1(ExcelUtils.parseDouble(trim));
                                break;
                            case 9:
                                excel08.setGyczCurrentaccumulate(ExcelUtils.parseDouble(trim));
                                break;
                            case 10:
                                excel08.setGyczPreviousaccumulate(ExcelUtils.parseDouble(trim));
                                break;
                            case 11:
                                excel08.setGyczMonthonmonth2(ExcelUtils.parseDouble(trim));
                                break;
                            case 12:
                                excel08.setNyxflCurrentaccumulate(ExcelUtils.parseDouble(trim));
                                break;
                            case 13:
                                excel08.setNyxflPreviousaccumulate(ExcelUtils.parseDouble(trim));
                                break;
                            case 14:
                                excel08.setNyxflMonthonmonth(ExcelUtils.parseDouble(trim));
                                break;
                            case 15:
                                excel08.setGyydlCurrentaccumulate(ExcelUtils.parseDouble(trim));
                                break;
                            case 16:
                                excel08.setGyydlPreviousaccumulate(ExcelUtils.parseDouble(trim));
                                break;
                            case 17:
                                excel08.setGyydlMonthonmonth(ExcelUtils.parseDouble(trim));
                                break;
                            case 18:
                                excel08.setSectorcode(ExcelUtils.parseInteger(trim));
                                break;
                            case 19:
                                excel08.setSectorname(trim);
                                break;
                            case 20:
                                excel08.setGroup(trim);
                                break;
                            case 21:
                                excel08.setPerson(trim);
                                break;
                            case 22:
                                excel08.setGxjsbj(ExcelUtils.parseInteger(trim));
                                break;
                            case 23:
                                excel08.setZdbj(ExcelUtils.parseInteger(trim));
                                break;
                            default:
                                return null;
                        }
                        return excel08;
                    });

            excel08Service.insertBatch(tList);
            return CallBackResult.ok();
        } catch (Exception e) {
            return CallBackResult.fail(e);
        }

    }

    @Override
    @TimeCostLog
    public CallBackResult uploadExcel09(Workbook wb, String sheetName, int startReadLine, Date date) {
        try {
            List<Excel09> tList = ExcelUtils.importExcel(wb, sheetName, startReadLine, date, Excel09.class,
                    (index, excel09, trim) -> {
                        switch (index) {
                            case 0:
                                excel09.setNumber(ExcelUtils.parseInteger(trim));
                            case 1:
                                excel09.setName(trim);
                                break;
                            case 2:
                                if (trim != null && trim.substring(trim.length() - 1).equals("镇"))
                                    trim = trim.substring(0, trim.length() - 1);
                                excel09.setArea(trim);
                                break;
                            case 3:
                                excel09.setOrganizationcode(trim);
                                break;
                            case 4:
                                excel09.setIndustrycode(ExcelUtils.parseInteger(trim));
                                break;
                            case 5:
                                excel09.setType(ExcelUtils.parseInteger(trim));
                                break;
                            case 6:
                                excel09.setYysrCurrentccumulate(ExcelUtils.parseDouble(trim));
                                break;
                            case 7:
                                excel09.setYysrPreviousaccumulate(ExcelUtils.parseDouble(trim));
                                break;
                            case 8:
                                excel09.setYysrMonthonmonth(ExcelUtils.parseDouble(trim));
                                break;
                            case 9:
                                excel09.setLrzeCurrentccumulate(ExcelUtils.parseDouble(trim));
                                break;
                            case 10:
                                excel09.setLrzePreviousaccumulate(ExcelUtils.parseDouble(trim));
                                break;
                            case 11:
                                excel09.setLrzeMonthonmonth(ExcelUtils.parseDouble(trim));
                                break;
                            case 12:
                                excel09.setLszeCurrentccumulate(ExcelUtils.parseDouble(trim));
                                break;
                            case 13:
                                excel09.setLszePreviousaccumulate(ExcelUtils.parseDouble(trim));
                                break;
                            case 14:
                                excel09.setLszeMonthonmonth(ExcelUtils.parseDouble(trim));
                                break;
                            case 15:
                                excel09.setSectorcode(ExcelUtils.parseInteger(trim));
                                break;
                            case 16:
                                excel09.setSectorname(trim);
                                break;
                            case 17:
                                excel09.setGroup(trim);
                                break;
                            case 18:
                                excel09.setPerson(trim);
                                break;
                            case 21:
                                excel09.setGxjsbj(ExcelUtils.parseInteger(trim));
                                break;
                            case 22:
                                excel09.setWhcybj(ExcelUtils.parseInteger(trim));
                                break;
                            case 23:
                                excel09.setZdbj(ExcelUtils.parseInteger(trim));
                                break;
                            default:
                                return null;

                        }
                        return excel09;
                    });
            excel09Service.insertBatch(tList);
            return CallBackResult.ok();
        } catch (Exception e) {
            return CallBackResult.fail(e);
        }

    }

    @Override
    @TimeCostLog
    public CallBackResult uploadExcel11(Workbook wb, String sheetName, int startReadLine, Date date) {
        try {
            List<Excel11> tList = ExcelUtils.importExcel(wb, sheetName, startReadLine, date, Excel11.class,
                    (index, excel11, trim) -> {
                        switch (index) {
                            case 0:
                                excel11.setNumber(ExcelUtils.parseInteger(trim));
                            case 1:
                                excel11.setName1(trim);
                                break;
                            case 2:
                                excel11.setOrganizationcode(trim);
                                break;
                            case 3:
                                excel11.setType(ExcelUtils.parseInteger(trim));
                                break;
                            case 4:
                                excel11.setIndustryCode(ExcelUtils.parseInteger(trim));
                                break;
                            case 5:
                                if (trim != null && trim.substring(trim.length() - 1).equals("镇"))
                                    trim = trim.substring(0, trim.length() - 1);
                                excel11.setArea(trim);
                                break;
                            case 6:
                                excel11.setName(trim);
                                break;
                            case 7:
                                excel11.setBj(ExcelUtils.parseInteger(trim));
                                break;
                            case 8:
                                excel11.setProjectIndustryCode(ExcelUtils.parseInteger(trim));
                                break;
                            case 9:
                                excel11.setCommencementDate(trim);
                                break;
                            case 10:
                                excel11.setPlannedInvestment(ExcelUtils.parseInteger(trim));
                                break;
                            case 11:
                                excel11.setCompletedInvestment(ExcelUtils.parseInteger(trim));
                                break;
                            case 12:
                                excel11.setCurrentmonth(ExcelUtils.parseInteger(trim));
                                break;
                            case 13:
                                excel11.setAccumulate(ExcelUtils.parseInteger(trim));
                                break;
                            case 14:
                                excel11.setGybj1(ExcelUtils.parseInteger(trim));
                                break;
                            case 15:
                                excel11.setGyxmbj1(ExcelUtils.parseInteger(trim));
                                break;
                            case 16:
                                excel11.setGxjsbj1(ExcelUtils.parseInteger(trim));
                                break;
                            case 17:
                                excel11.setXxcybj1(ExcelUtils.parseInteger(trim));
                                break;
                            case 18:
                                excel11.setLxjtbj1(ExcelUtils.parseInteger(trim));
                                break;
                            case 19:
                                excel11.setYbzdbj1(ExcelUtils.parseInteger(trim));
                                break;
                            case 20:
                                excel11.setXmrkny(ExcelUtils.parseInteger(trim));
                                break;
                            default:
                                return null;
                        }
                        return excel11;
                    });

            excel11Service.insertBatch(tList);
            return CallBackResult.ok();
        } catch (Exception e) {
            return CallBackResult.fail(e);
        }

    }

    @Override
    @TimeCostLog
    public CallBackResult uploadExcel12(Workbook wb, String sheetName, int startReadLine, Date date) {
        try {
            List<Excel12> tList = ExcelUtils.importExcel(wb, sheetName, startReadLine, date, Excel12.class,
                    (index, excel12, trim) -> {
                        switch (index) {
                            case 0:
                                excel12.setNumber(ExcelUtils.parseInteger(trim));
                            case 1:
                                excel12.setName1(trim);
                                break;
                            case 2:
                                excel12.setZzjgdm(trim);
                                break;
                            case 3:
                                excel12.setDjzcCode(ExcelUtils.parseInteger(trim));
                                break;
                            case 4:
                                excel12.setIndustryCode(ExcelUtils.parseInteger(trim));
                                break;
                            case 5:
                                if (trim != null && trim.substring(trim.length() - 1).equals("镇"))
                                    trim = trim.substring(0, trim.length() - 1);
                                excel12.setArea(trim);
                                break;
                            case 6:
                                excel12.setName2(trim);
                                break;
                            case 7:
                                excel12.setBj(ExcelUtils.parseInteger(trim));
                                break;
                            case 8:
                                excel12.setCommencementDate(trim);
                                break;
                            case 9:
                                excel12.setPlannedInvestment(ExcelUtils.parseInteger(trim));
                                break;
                            case 10:
                                excel12.setPlannedGzf(ExcelUtils.parseInteger(trim));
                                break;
                            case 11:
                                excel12.setCompletedInvestment(ExcelUtils.parseInteger(trim));
                                break;
                            case 12:
                                excel12.setCurrentmonth(ExcelUtils.parseInteger(trim));
                                break;
                            case 13:
                                excel12.setAccumulate(ExcelUtils.parseInteger(trim));
                                break;
                            case 14:
                                excel12.setBnxsmj(ExcelUtils.parseInteger(trim));
                                break;
                            case 15:
                                excel12.setBnxse(ExcelUtils.parseInteger(trim));
                                break;
                            case 16:
                                excel12.setXmrkny(ExcelUtils.parseInteger(trim));
                                break;
                            default:
                                return null;
                        }
                        return excel12;
                    });

            excel12Service.insertBatch(tList);
            return CallBackResult.ok();
        } catch (Exception e) {
            return CallBackResult.fail(e);
        }

    }

    @Override
    @TimeCostLog
    public CallBackResult uploadExcel14(Workbook wb, String sheetName, int startReadLine, Date date) {
        try {
            List<Excel14> tList = ExcelUtils.importExcel(wb, sheetName, startReadLine, date, Excel14.class,
                    (index, excel14, trim) -> {
                        switch (index) {
                            case 0:
                                excel14.setNumber(ExcelUtils.parseInteger(trim));
                            case 1:
                                excel14.setName(trim);
                                break;
                            case 2:
                                if (trim != null && trim.substring(trim.length() - 1).equals("镇"))
                                    trim = trim.substring(0, trim.length() - 1);
                                excel14.setArea(trim);
                                break;
                            case 3:
                                excel14.setOrganizationcode(trim);
                                break;
                            case 4:
                                excel14.setIndustrycode(ExcelUtils.parseInteger(trim));
                                break;
                            case 5:
                                excel14.setType(ExcelUtils.parseInteger(trim));
                                break;
                            case 6:
                                excel14.setCurrentmonth(ExcelUtils.parseDouble(trim));
                                break;
                            case 7:
                                excel14.setPreviousmonth(ExcelUtils.parseDouble(trim));
                                break;
                            case 8:
                                excel14.setMonthonmonth1(ExcelUtils.parseDouble(trim));
                                break;
                            case 9:
                                excel14.setCurrentaccumulate(ExcelUtils.parseDouble(trim));
                                break;
                            case 10:
                                excel14.setPreviousaccumulate(ExcelUtils.parseDouble(trim));
                                break;
                            case 11:
                                excel14.setMonthonmonth2(ExcelUtils.parseDouble(trim));
                                break;
                            case 12:
                                excel14.setSectorname(trim);
                                break;
                            case 13:
                                excel14.setYlxbj1(ExcelUtils.parseInteger(trim));
                                break;
                            case 14:
                                excel14.setWhcybj1(ExcelUtils.parseInteger(trim));
                                break;
                            case 15:
                                excel14.setZdbj(ExcelUtils.parseInteger(trim));
                                break;
                            default:
                                return null;
                        }
                        return excel14;
                    });

            excel14Service.insertBatch(tList);
            return CallBackResult.ok();
        } catch (Exception e) {
            return CallBackResult.fail(e);
        }

    }

    @Override
    @TimeCostLog
    public CallBackResult uploadExcel15(Workbook wb, String sheetName, int startReadLine, Date date) {
        try {
            List<Excel15> tList = ExcelUtils.importExcel(wb, sheetName, startReadLine, date, Excel15.class,
                    (index, excel15, trim) -> {
                        switch (index) {
                            case 0:
                                excel15.setNumber(ExcelUtils.parseInteger(trim));
                            case 1:
                                excel15.setName(trim);
                                break;
                            case 2:
                                if (trim != null && trim.substring(trim.length() - 1).equals("镇"))
                                    trim = trim.substring(0, trim.length() - 1);
                                excel15.setArea(trim);
                                break;
                            case 3:
                                excel15.setOrganizationcode(trim);
                                break;
                            case 4:
                                excel15.setIndustrycode(ExcelUtils.parseInteger(trim));
                                break;
                            case 5:
                                excel15.setType(ExcelUtils.parseInteger(trim));
                                break;
                            case 6:
                                excel15.setCurrentmonth(ExcelUtils.parseDouble(trim));
                                break;
                            case 7:
                                excel15.setPreviousmonth(ExcelUtils.parseDouble(trim));
                                break;
                            case 8:
                                excel15.setMonthonmonth1(ExcelUtils.parseDouble(trim));
                                break;
                            case 9:
                                excel15.setCurrentaccumulate(ExcelUtils.parseDouble(trim));
                                break;
                            case 10:
                                excel15.setPreviousaccumulate(ExcelUtils.parseDouble(trim));
                                break;
                            case 11:
                                excel15.setMonthonmonth2(ExcelUtils.parseDouble(trim));
                                break;
                            case 12:
                                excel15.setSectorname(trim);
                                break;
                            case 13:
                                excel15.setWhcybj1(ExcelUtils.parseInteger(trim));
                                break;
                            case 14:
                                excel15.setZdbj(ExcelUtils.parseInteger(trim));
                                break;
                            default:
                                return null;
                        }
                        return excel15;
                    });

            excel15Service.insertBatch(tList);
            return CallBackResult.ok();
        } catch (Exception e) {
            return CallBackResult.fail(e);
        }

    }

    /**
     * 11基础表投资（工投基础）
     * 计算 -> 全社会固定资产投资、
     * 工业投资（表11中工业项目标记为1的）
     * 基础设施项目投资（表11中除工业项目标记为1的）
     *
     * @param date
     */
    @Override
    public void sheet11Cal(Date date) {
        String year = String.valueOf(TimeUtil.year(date));
        String month = String.valueOf(TimeUtil.month(date));
        FixedInvestment industrialInvestmentInfo = excel11Service.getIndustrialInvestmentInfo(year, month);
        FixedInvestment basicInvestmentInfo = excel11Service.getBasicInvestmentInfo(year, month);
        FixedInvestment socialFixedInvestmentInfo = excel11Service.getSocialFixedInvestmentInfo(year, month);
        if (industrialInvestmentInfo == null || basicInvestmentInfo == null || socialFixedInvestmentInfo == null)
            return;
        // 工业投资
        fixedInvestmentService.removeByIndicator(date, "工业投资");
        fixedInvestmentService.insert(industrialInvestmentInfo);
        // 1表
        EconomicIndicators economicIndicators1 = economicIndicatorsService.queryByIndicator(date, "#工业投资");
        if (economicIndicators1 != null) {
            economicIndicators1.setThisMonth(industrialInvestmentInfo.getThisMonth());
            economicIndicators1.setAccumulate(industrialInvestmentInfo.getAccumulate());
            economicIndicators1.setMonthOnMonth(industrialInvestmentInfo.getMonthOnMonth());
//            economicIndicators1.setSchedule(MathUtil.round(economicIndicators1.getAccumulate()/Double.parseDouble(economicIndicators1.getTotal())*100,1));
            economicIndicatorsService.update(economicIndicators1);
        }
        // 基础设施项目投资
        fixedInvestmentService.removeByIndicator(date, "基础设施项目投资");
        fixedInvestmentService.insert(basicInvestmentInfo);
        // 全社会固定资产投资
        fixedInvestmentService.removeByIndicator(date, "全社会固定资产投资");
        fixedInvestmentService.insert(socialFixedInvestmentInfo);
        // 经济1表
        EconomicIndicators economicIndicators = economicIndicatorsService.queryByIndicator(date, "全社会固定资产投资");
        if (economicIndicators != null) {
            economicIndicators.setThisMonth(socialFixedInvestmentInfo.getThisMonth());
            economicIndicators.setAccumulate(socialFixedInvestmentInfo.getAccumulate());
            economicIndicators.setMonthOnMonth(socialFixedInvestmentInfo.getMonthOnMonth());
//            economicIndicators.setSchedule(MathUtil.round(economicIndicators.getAccumulate()/Double.parseDouble(economicIndicators.getTotal())*100,1));
            economicIndicatorsService.update(economicIndicators);
        }
        // 递归
        sheet11Cal(TimeUtil.date(String.valueOf(Integer.parseInt(year) + 1), month));

    }

    /**
     * 12基础表投资（房地产）
     * 计算 -> 房地产投资
     *
     * @param date
     */
    @Override
    public void sheet12Cal(Date date) {
        String year = String.valueOf(TimeUtil.year(date));
        String month = String.valueOf(TimeUtil.month(date));
        // 房地产投资
        FixedInvestment realEstateInvestmentInfo = excel12Service.getRealEstateInvestmentInfo(year, month);
        // 递归退出
        if (realEstateInvestmentInfo == null) return;
        fixedInvestmentService.removeByIndicator(date, "#房地产投资");
        fixedInvestmentService.insert(realEstateInvestmentInfo);
        // 递归修改房地产投资数据
        sheet12Cal(TimeUtil.date(String.valueOf(Integer.parseInt(year) + 1), month));
    }

    /**
     * 8基础表工业分行业（产值能耗）
     * 计算 -> 规上工业总产值、综合能源消费量（吨标准煤）、规上工业用电量（万千瓦时）
     * 规上工业用电量（万千瓦时） 高新技术产业产值
     *
     * @param date
     */
    @Override
    public void sheet8Cal(Date date) {
        String year = String.valueOf(TimeUtil.year(date));
        String month = String.valueOf(TimeUtil.month(date));
        // 规上工业总产值
        IndustrialEconomicIndicators industryOutputInfo = excel08Service.getIndustryOutputInfo(year, month);
        industrialEconomicIndicatorsService.removeByIndicator(date, "#规上工业总产值");
        industrialEconomicIndicatorsService.insert(industryOutputInfo);
        // 经济1表
        EconomicIndicators economicIndicators = economicIndicatorsService.queryByIndicator(date, "规上工业总产值");
        if (economicIndicators != null) {
            economicIndicators.setThisMonth(industryOutputInfo.getThisMonth());
            economicIndicators.setAccumulate(industryOutputInfo.getAccumulate());
            economicIndicators.setMonthOnMonth(industryOutputInfo.getMonthOnMonth());
//            economicIndicators.setSchedule(MathUtil.round(economicIndicators.getAccumulate()/Double.parseDouble(economicIndicators.getTotal())*100,1));
            economicIndicatorsService.update(economicIndicators);
        }
        // 综合能源消费量（吨标准煤）
        for (int i = 1; i <= 12; i++) {
            IndustrialEconomicIndicators energyConsumptionInfo = excel08Service.getEnergyConsumptionInfo(year,
                    String.valueOf(i));
            if (energyConsumptionInfo != null) {
                industrialEconomicIndicatorsService.removeByIndicator(TimeUtil.date(year, String.valueOf(i)),
                        "综合能源消费量（吨标准煤）");
                industrialEconomicIndicatorsService.insert(energyConsumptionInfo);
            }
        }

        // 规上工业用电量（万千瓦时）
        // 遍历12个月
        for (int i = 1; i <= 12; i++) {
            IndustrialEconomicIndicators industrialElectricityInfo = excel08Service.getIndustrialElectricityInfo(year,
                    String.valueOf(i));
            if (industrialElectricityInfo != null) {
                industrialEconomicIndicatorsService.removeByIndicator(TimeUtil.date(year, String.valueOf(i)),
                        "规上工业用电量（万千瓦时）");
                industrialEconomicIndicatorsService.insert(industrialElectricityInfo);
            }
        }
        // 万元产值能耗（吨标准煤/万元）
        for (int i = 1; i <= 12; i++) {
            IndustrialEconomicIndicators industrialEconomicIndicators = excel08Service.getEnergyConsumption1wInfo(year,
                    String.valueOf(i));
            if (industrialEconomicIndicators != null) {
                industrialEconomicIndicatorsService.removeByIndicator(TimeUtil.date(year, String.valueOf(i)),
                        "万元产值能耗（吨标准煤/万元）");
                industrialEconomicIndicatorsService.insert(industrialEconomicIndicators);
            }
        }

        // 高新技术产业产值
        IndustrialEconomicIndicators highTechInfo = excel08Service.getHighTechInfo(year, month);
        industrialEconomicIndicatorsService.removeByIndicator(date, "高新技术产业产值");
        industrialEconomicIndicatorsService.insert(highTechInfo);
        // 高薪占比
        IndustrialEconomicIndicators highTechProportionInfo = excel08Service.getHighTechProportionInfo(year, month);
        industrialEconomicIndicatorsService.removeByIndicator(date, "高新占比 %");
        industrialEconomicIndicatorsService.insert(highTechProportionInfo);
    }

    /**
     * 主要计算 利润和利税
     *
     * @param date
     */
    @Override
    public void sheet9Cal(Date date) {
        String year = String.valueOf(TimeUtil.year(date));
        String month = String.valueOf(TimeUtil.month(date));
        // 利润总额
        IndustrialEconomicIndicators totalProfit = excel09Service.getTotalProfit(year, month);
        industrialEconomicIndicatorsService.removeByIndicator(date, "利润总额");
        industrialEconomicIndicatorsService.insert(totalProfit);
        // 利税总额
        IndustrialEconomicIndicators totalTaxes = excel09Service.getTotalTaxes(year, month);
        industrialEconomicIndicatorsService.removeByIndicator(date, "利税总额");
        industrialEconomicIndicatorsService.insert(totalTaxes);
    }

    @Override
    public void sheet14Cal(Date date) {
        String year = String.valueOf(TimeUtil.year(date));
        String month = String.valueOf(TimeUtil.month(date));
        //交通
        TradeAndServiceIndustry info = excel14Service.getTrafficTurnoverTotal(year, month);
        tradeAndServiceIndustryService.removeByIndicator(date, "交通及营利性服务业营业额");
        tradeAndServiceIndustryService.insert(info);
    }

    @Override
    public void sheet15Cal(Date date) {
        String year = String.valueOf(TimeUtil.year(date));
        String month = String.valueOf(TimeUtil.month(date));
        // 批发业
        TradeAndServiceIndustry wholesaleTurnoverTotal = excel15Service.getWholesaleTurnoverTotal(year, month);
        tradeAndServiceIndustryService.removeByIndicator(date, "限上批发业销售额");
        tradeAndServiceIndustryService.insert(wholesaleTurnoverTotal);
        // 零售业
        TradeAndServiceIndustry retailTurnoverTotal = excel15Service.getRetailTurnoverTotal(year, month);
        tradeAndServiceIndustryService.removeByIndicator(date, "限上零售业销售额");
        tradeAndServiceIndustryService.insert(retailTurnoverTotal);
        // 住宿业
        TradeAndServiceIndustry lodgingTurnoverTotal = excel15Service.getLodgingTurnoverTotal(year, month);
        tradeAndServiceIndustryService.removeByIndicator(date, "限上住宿业营业额");
        tradeAndServiceIndustryService.insert(lodgingTurnoverTotal);
        // 餐饮业
        TradeAndServiceIndustry cateringTurnoverTotal = excel15Service.getCateringTurnoverTotal(year, month);
        tradeAndServiceIndustryService.removeByIndicator(date, "限上餐饮业营业额");
        tradeAndServiceIndustryService.insert(cateringTurnoverTotal);
    }

    /**
     * 计算excel值
     *
     * @param date
     */
    @Override
    public void calculateExcel(Date date) {
        sheet8Cal(date);
        sheet9Cal(date);
        sheet11Cal(date);
        sheet12Cal(date);
        sheet14Cal(date);
        sheet15Cal(date);
        sheet1Cal(date);
    }


    /**
     * 用于外贸的计算
     *
     * @param date
     */
    public void sheet1Cal(Date date) {
        int year = TimeUtil.year(date);
        int month = TimeUtil.month(date);
        if (month == 1) return; // 1月无数据保存直接返回
        EconomicIndicators economicIndicators = economicIndicatorsService.queryByIndicator(date, "实际使用外资");
        if (economicIndicators == null) return;
        if (month == 2) {
            // 当为二月时
            economicIndicators.setThisMonth(economicIndicators.getAccumulate());// 将累计值直接传给当月
            // 保存数据
            economicIndicatorsService.update(economicIndicators);
        } else {
            // 查询上一个月数据
            EconomicIndicators lastQuery = economicIndicatorsService.queryByIndicator(TimeUtil.date(year, month - 1), "实际使用外资");
            if (lastQuery == null) return;
            economicIndicators.setThisMonth(economicIndicators.getAccumulate() - lastQuery.getAccumulate());
            // 保存数据
            economicIndicatorsService.update(economicIndicators);
        }
    }

    /**
     * 返回当前excel月份是否重复
     *
     * @param date 年月
     * @return
     */
    @Override
    public Boolean checkExcel(Date date) {
        int res = excelMapper.checkExcel(date);
        return res == 0;
    }

    /**
     * 删除指定月份所有数据
     *
     * @param date
     */
    @Override
    @TimeCostLog
    public void removeAllExcel(Date date) {
        economicIndicatorsService.removeByDate(date);
        subDistrictTownIndustryService.removeByDate(date);
        industrialEconomicIndicatorsService.removeByDate(date);
        subDistrictTownFixedInvestmentService.removeByDate(date);
        subDistrictTownIndustrialInvestmentService.removeByDate(date);
        fixedInvestmentService.removeByDate(date);
        socialRetailSalesService.removeByDate(date);
        tradeAndServiceIndustryService.removeByDate(date);
        excel08Service.removeByDate(date);
        excel02Service.removeByDate(date);
        excel11Service.removeByDate(date);
        excel12Service.removeByDate(date);
        excel09Service.removeByDate(date);
        excel14Service.removeByDate(date);
        excel15Service.removeByDate(date);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean importFormerData(MultipartFile file, Date date) {
        Workbook wb = ExcelUtils.getWorkbook(file);
        int year = TimeUtil.year(date);
        uploadEconomicIndicatorsExcel(wb, "2021年1-2月", 3, TimeUtil.date(year, 2));
        sheet11Cal(TimeUtil.date(year + 1, 2));

        uploadEconomicIndicatorsExcel(wb, "2021年3月", 3, TimeUtil.date(year, 3));
        sheet11Cal(TimeUtil.date(year + 1, 3));

        uploadEconomicIndicatorsExcel(wb, "2021年4月", 3, TimeUtil.date(year, 4));
        sheet11Cal(TimeUtil.date(year + 1, 4));

        uploadEconomicIndicatorsExcel(wb, "2021年5月", 3, TimeUtil.date(year, 5));
        sheet11Cal(TimeUtil.date(year + 1, 5));

        uploadEconomicIndicatorsExcel(wb, "2021年6月", 3, TimeUtil.date(year, 6));
        sheet11Cal(TimeUtil.date(year + 1, 6));

        uploadEconomicIndicatorsExcel(wb, "2021年7月", 3, TimeUtil.date(year, 7));
        sheet11Cal(TimeUtil.date(year + 1, 7));

        uploadEconomicIndicatorsExcel(wb, "2021年8月", 3, TimeUtil.date(year, 8));
        sheet11Cal(TimeUtil.date(year + 1, 8));

        uploadEconomicIndicatorsExcel(wb, "2021年9月", 3, TimeUtil.date(year, 9));
        sheet11Cal(TimeUtil.date(year + 1, 9));

        uploadEconomicIndicatorsExcel(wb, "2021年10月", 3, TimeUtil.date(year, 10));
        sheet11Cal(TimeUtil.date(year + 1, 10));

        uploadEconomicIndicatorsExcel(wb, "2021年11月", 3, TimeUtil.date(year, 11));
        sheet11Cal(TimeUtil.date(year + 1, 11));

        uploadEconomicIndicatorsExcel(wb, "2021年12月", 3, TimeUtil.date(year, 12));
        sheet11Cal(TimeUtil.date(year + 1, 12));

        return true;
    }


    @Override
    public Date getLatestDataTime() {
        return economicIndicatorsService.getLatestDataTime();
    }
}